import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import styles from './Login.module.css';
import { login, changePassword } from '@/utils/auth';

const Login: React.FC = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [verificationCode, setVerificationCode] = useState('');
  const [simulatedCode, setSimulatedCode] = useState('');
  const [isVerified, setIsVerified] = useState(false);
  const [showVerificationInput, setShowVerificationInput] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const [isChangePassword, setIsChangePassword] = useState(false);
  const [changeSuccess, setChangeSuccess] = useState(false);
  const navigate = useNavigate();

  // 模拟发送验证码
  const sendVerificationCode = () => {
    // 生成随机验证码并显示（模拟发送到用户手机/邮箱）
    const code = Math.floor(100000 + Math.random() * 900000).toString();
    setSimulatedCode(code);
    alert(`验证码已发送：${code}（实际环境中会发送到用户邮箱或手机）`);
    setShowVerificationInput(true);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);
    setError('');

    try {
        if (isChangePassword) {
          // 修改密码需要先验证
          if (!isVerified) {
            // 验证输入的验证码
            if (verificationCode !== simulatedCode) {
              setError('验证码错误');
              return;
            }
            setIsVerified(true);
            setShowVerificationInput(false);
            setError('');
            return;
          }
          
          // 验证码验证通过后，调用修改密码API
          await changePassword(username, newPassword);
          setChangeSuccess(true);
          setError('');
          // 修改成功后重置表单并返回登录界面
          setTimeout(() => {
            setIsChangePassword(false);
            setChangeSuccess(false);
            setNewPassword('');
            setPassword('');
            setVerificationCode('');
            setIsVerified(false);
            setShowVerificationInput(false);
          }, 2000);
        } else {
          // 直接调用登录API
          const success = await login(username, password);
          if (success) {
            // 登录成功后跳转到首页
            navigate('/');
          } else {
            setError('用户名或密码错误');
          }
        }
      } catch (err: unknown) {
      setError(err instanceof Error ? err.message : (isChangePassword ? '修改密码失败，请稍后重试' : '登录失败，请稍后重试'));
      console.error(isChangePassword ? 'Change password error:' : 'Login error:', err);
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.loginContainer}>
      <div className={styles.loginGrid} />
      <div className={styles.loginAurora} />

      <div className={styles.loginBox}>
        <div className={styles.hologram}>
          <span className={styles.holoPulse} />
          <span className={styles.holoPulse} />
        </div>

        <div className={styles.idBadge}>
          <div className={styles.badgeAvatar}>
            <span className={styles.badgeGlare} />
            <svg viewBox="0 0 24 24" className={styles.badgeIcon} aria-hidden="true">
              <path
                d="M12 3l7.5 4.33v8.34L12 20l-7.5-4.33V7.33L12 3zm0 2.31L6.5 8.02v7.96L12 18.69l5.5-2.71V8.02L12 5.31zm0 4.19a3.5 3.5 0 013.5 3.5h-2a1.5 1.5 0 00-3 0h-2a3.5 3.5 0 013.5-3.5zm4 5a4 4 0 01-8 0h2a2 2 0 004 0h2z"
                fill="currentColor"
              />
            </svg>
          </div>
          <div className={styles.badgeMeta}>
            <span className={styles.badgeLabel}>NEXUS SECURE GATEWAY</span>
            <span className={styles.badgeDesc}>E-Commerce Control Core v5.2</span>
          </div>
          <span className={styles.badgeStatus}>
            <span className={styles.statusPulse} />
            ONLINE
          </span>
        </div>

        <div className={styles.sectionDivider} />

        <div className={styles.titleCluster}>
          <h2 className={styles.loginTitle}>{isChangePassword ? '身份校验 · 重置密码' : '登录电商后台管理枢纽'}</h2>
          {!isChangePassword && (
            <p className={styles.loginSubtitle}>一体化调度 · 全局可观测 · AI 辅助守护业务安全</p>
          )}
        </div>
        
        {changeSuccess && (
          <div className={styles.successMessage}>密码修改成功！正在返回登录页面...</div>
        )}
        
        {error && <div className={styles.errorMessage}>{error}</div>}
        
        <form onSubmit={handleSubmit} className={styles.loginForm}>
          <div className={styles.formGroup}>
            <label className={styles.formLabel} htmlFor="username">用户名</label>
            <input
              type="text"
              id="username"
              className={styles.formInput}
              value={username}
              onChange={(e) => setUsername(e.target.value)}
              placeholder="请输入用户名"
              required
              disabled={loading}
            />
          </div>

          {isChangePassword ? (
            <>
              {!isVerified ? (
                // 验证阶段
                <div className={styles.formGroup}>
                  <label className={styles.formLabel} htmlFor="verificationCode">验证身份</label>
                  <div style={{ display: 'flex', gap: '10px', alignItems: 'flex-end' }}>
                    <input
                      type="text"
                      id="verificationCode"
                      className={styles.formInput}
                      value={verificationCode}
                      onChange={(e) => setVerificationCode(e.target.value)}
                      placeholder="请输入验证码"
                      required
                      disabled={loading}
                      style={{ flex: 1 }}
                    />
                    <button
                      type="button"
                      className={styles.secondaryButton}
                      onClick={sendVerificationCode}
                      disabled={loading || !username}
                    >
                      发送验证码
                    </button>
                  </div>
                  {showVerificationInput && (
                    <p style={{ fontSize: '12px', color: '#666', marginTop: '5px' }}>请输入验证码以验证您的身份</p>
                  )}
                </div>
              ) : (
                // 验证通过后的密码修改阶段
                <div className={styles.formGroup}>
                  <label className={styles.formLabel} htmlFor="newPassword">新密码</label>
                  <input
                    type="password"
                    id="newPassword"
                    className={styles.formInput}
                    value={newPassword}
                    onChange={(e) => setNewPassword(e.target.value)}
                    placeholder="请输入新密码"
                    required
                    disabled={loading}
                  />
                </div>
              )}
            </>
          ) : (
            <>
              <div className={styles.formGroup}>
                <label className={styles.formLabel} htmlFor="password">密码</label>
                <input
                  type="password"
                  id="password"
                  className={styles.formInput}
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  placeholder="请输入密码"
                  required
                  disabled={loading}
                />
              </div>
            </>
          )}

          <button
            type="submit"
            className={styles.loginButton}
            disabled={loading}
          >
            {loading ? 
              (isChangePassword ? 
                (isVerified ? '修改中...' : '验证中...') : 
                '登录中...') : 
              (isChangePassword ? 
                (isVerified ? '修改密码' : '验证身份') : 
                '登录')}
          </button>
        </form>

        <button
          type="button"
          className={styles.toggleButton}
          onClick={() => {
            setIsChangePassword(!isChangePassword);
            setError('');
            setChangeSuccess(false);
            setIsVerified(false);
            setShowVerificationInput(false);
            setVerificationCode('');
            if (!isChangePassword) {
              setPassword('');
            }
          }}
        >
          {isChangePassword ? '← 返回登录终端' : '忘记密码？启动身份校验'}
        </button>

        {!isChangePassword && (
          <ul className={styles.loginHighlights}>
            <li>
              <span className={styles.highlightDot} />
              零信任登录管控 · 多因子加固
            </li>
            <li>
              <span className={styles.highlightDot} />
              实时审计溯源 · 风险即刻预警
            </li>
            <li>
              <span className={styles.highlightDot} />
              动态配置推送 · 秒级热更新
            </li>
          </ul>
        )}

        <div className={styles.loginFooter}>
          <p className={styles.footerText}>
            {isChangePassword
              ? '安全提示：请使用 12 位以上复杂密码，避免与历史密码重复。'
              : '登录即视为授权接入电商后台管理系统 · 全链路操作将被实时监控。'}
          </p>
        </div>
      </div>
    </div>
  );
};

export default Login;